package com.sharif.cn;

import io.github.resilience4j.bulkhead.Bulkhead;
import io.github.resilience4j.bulkhead.BulkheadConfig;
import io.github.resilience4j.bulkhead.BulkheadRegistry;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.time.Duration;
import java.util.function.Supplier;

import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;

@Activate(order=50,group={PROVIDER})
public class BulkheadFilter implements Filter {

    private BulkheadRegistry registry;

    public BulkheadFilter() {

    }

    public BulkheadRegistry init()
    {
        BulkheadConfig config = BulkheadConfig.custom()
                .maxConcurrentCalls(1)
                .maxWaitDuration(Duration.ofMillis(0))
                .build();
        registry = BulkheadRegistry.of(config);
        return registry;
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Supplier<Result> decoratedSupplier = Bulkhead.decorateSupplier(registry.bulkhead("sharif"), ()->invoker.invoke(invocation));
        return decoratedSupplier.get();
    }

    public static void main(String[] args) {
        BulkheadFilter bulkheadFilter = new BulkheadFilter();
        BulkheadRegistry registry = bulkheadFilter.init();
        for(int i=0;i<10;i++)
        {
            new Thread()
            {
                @Override
                public void run() {
                    for(int j=0;j<10;j++)
                    {
                        Supplier<String> decoratedSupplier = Bulkhead.decorateSupplier(registry.bulkhead("sharif"), ()->"111");
                        System.out.println(decoratedSupplier.get());
                    }
                }
            }.start();
        }
    }
}
